//
//  ViewController.m
//  Bluetooth Tests
//
//  Created by Zack Brody on 7/13/13.
//  Copyright (c) 2013 Zack Brody. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize currentSession;
@synthesize connect;
@synthesize disconnect;

GKPeerPickerController *picker;

- (void)viewDidLoad
{
    [connect setHidden:NO];
    [disconnect setHidden:YES];
    [super viewDidLoad];
    image = [[UIImage alloc]init];
    image = [UIImage imageNamed:@"ball.png"];
    image2 = [[UIImage alloc]init];
    image2 = [UIImage imageNamed:@"ball2.png"];
    timer = [NSTimer scheduledTimerWithTimeInterval:0.033 target:self selector:@selector(update) userInfo:nil repeats:YES];
    particles = [[NSMutableArray alloc]init];
    previousPoint = CGPointMake(160, 240);
    self.view.multipleTouchEnabled = TRUE;
    selectionHasBeenChecked = false;
}


-(IBAction) btnConnectLeft:(id) sender {
    selectedButton = 1;
    picker = [[GKPeerPickerController alloc] init];
    picker.delegate = self;
    picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
    [leftConnectButton setHidden:YES];
    [rightConnectButton setHidden:YES];
    [disconnect setHidden:NO];
    [picker show];
}
-(IBAction) btnConnectRight:(id) sender {
    selectedButton = 2;
    picker = [[GKPeerPickerController alloc] init];
    picker.delegate = self;
    picker.connectionTypesMask = GKPeerPickerConnectionTypeNearby;
    [leftConnectButton setHidden:YES];
    [rightConnectButton setHidden:YES];
    [disconnect setHidden:NO];
    [picker show];
}

- (void)peerPickerController:(GKPeerPickerController *)picker
              didConnectPeer:(NSString *)peerID
                   toSession:(GKSession *) session {
    self.currentSession = session;
    session.delegate = self;
    [session setDataReceiveHandler:self withContext:nil];
    picker.delegate = nil;
    
    [picker dismiss];
}

- (void)peerPickerControllerDidCancel:(GKPeerPickerController *)picker
{
    picker.delegate = nil;
    
    [leftConnectButton setHidden:NO];
    [rightConnectButton setHidden:NO];
    [disconnect setHidden:YES];
}

-(IBAction) btnDisconnect:(id) sender {
    [self.currentSession disconnectFromAllPeers];
    currentSession = nil;
    
    [leftConnectButton setHidden:NO];
    [rightConnectButton setHidden:NO];
    [disconnect setHidden:YES];
}

- (void)session:(GKSession *)session
           peer:(NSString *)peerID
 didChangeState:(GKPeerConnectionState)state {
    switch (state)
    {
        case GKPeerStateConnected:
            NSLog(@"connected");
            [self mySendDataToPeers:[[NSString stringWithFormat:@"SELECTEDBUTTON:::%d", selectedButton] dataUsingEncoding:NSASCIIStringEncoding]];
            [self mySendDataToPeers:[[NSString stringWithFormat:@"SETSCREENDIMENSIONS::%f::%f", [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.height] dataUsingEncoding:NSASCIIStringEncoding]];
            for(int i = 0; i < particles.count; i++)
            {
                Particle *p = [particles objectAtIndex:i];
                [p.image removeFromSuperview];
                [particles removeObjectAtIndex:i];
            }
            break;
        case GKPeerStateDisconnected:
            NSLog(@"disconnected");
            for(int i = 0; i < particles.count; i++)
            {
                Particle *p = [particles objectAtIndex:i];
                [p.image removeFromSuperview];
                [particles removeObjectAtIndex:i];
            }
            [self btnDisconnect:nil];
            selectionHasBeenChecked = false;
            self.view.frame = [[UIScreen mainScreen] bounds];
            break;
        case GKPeerStateAvailable:
        case GKPeerStateConnecting:
        case GKPeerStateUnavailable:
            break;
    }
}

- (void) mySendDataToPeers:(NSData *) data
{
    if (currentSession)
        [self.currentSession sendDataToAllPeers:data
                                   withDataMode:GKSendDataReliable
                                          error:nil];
}


- (void) receiveData:(NSData *)data
            fromPeer:(NSString *)peer
           inSession:(GKSession *)session
             context:(void *)context {
    
   
    
    //---convert the NSData to NSString---
    //NSLog([@"Data :" stringByAppendingFormat:[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding]]);
    //NSLog([@"Device id:" stringByAppendingFormat:[NSString stringWithFormat:@"%d", selectedButton]]);
    if ([[[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@"::"] objectAtIndex:0] isEqualToString:@"SETSCREENDIMENSIONS"]) {
        int screenWidth = [[[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@"::"] objectAtIndex:1] intValue];
        int screenHeight = [[[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@"::"] objectAtIndex:2] intValue];
        NSLog([NSString stringWithFormat:@"%d", screenWidth]);
        NSLog([NSString stringWithFormat:@"%d", screenHeight]);
        totalScreenWidth = screenWidth + [[UIScreen mainScreen] bounds].size.width;
        
        if (screenHeight > [[UIScreen mainScreen] bounds].size.height) {
            totalScreenHeight = screenHeight;
        } else {
            totalScreenHeight = [[UIScreen mainScreen] bounds].size.height;
        }
        if (selectedButton == 1) {
            self.view.frame = CGRectMake(0, 0, totalScreenWidth, totalScreenHeight);
        }
        if(selectedButton == 2)
        {
            self.view.frame = CGRectMake(-(totalScreenWidth - [[UIScreen mainScreen] bounds].size.width), 0, totalScreenWidth, totalScreenHeight);
        }
        if(totalScreenWidth > 640)
        {
            maxParticles = 10;
        } else {
            maxParticles = 5;
        }
    }
    
    NSLog([NSString stringWithFormat:@"Screen Height: %f ScreenWidth: %f", totalScreenHeight, totalScreenWidth]);
    
    
    if (([[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] intValue] != (0 && 1)) && (data != [[NSString stringWithFormat:@"DISCONNECTEDFORSAMEBUTTONPRESSED"] dataUsingEncoding:NSASCIIStringEncoding])) {
        NSMutableArray *particleInfo = [[NSMutableArray alloc]initWithArray:[[[NSString alloc]initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@" "]];
        [particleInfo removeLastObject];
        dataString = [[NSString alloc]initWithFormat:@""];
        
        for (int i = 0; i < particleInfo.count; i += 4) {
            ptTouch = CGPointMake([[particleInfo objectAtIndex:i]floatValue], [[particleInfo objectAtIndex:(i + 1)]floatValue]);
            previousPoint = CGPointMake([[particleInfo objectAtIndex:(i + 2)]floatValue], [[particleInfo objectAtIndex:(i + 3)]floatValue]);
            int maxLifeTime = 10;
            
        
                for (int i = 0; i < 1; i++) {
                    Particle *particle = [[Particle alloc]init:image];
                    particle.image.center = CGPointMake(ptTouch.x, ptTouch.y);
                    particle.velocityX = (previousPoint.x - ptTouch.x);
                    particle.velocityY = (previousPoint.y - ptTouch.y);
                    particle.lifetime = arc4random() % maxLifeTime + 30;
                    [particles insertObject:particle atIndex:0];
                    [self.view addSubview:particle.image];
                
            }
        }
    }
    
    if(selectionHasBeenChecked == false)
    {
    
        if ((selectedButton == [[[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@":::"] objectAtIndex:1] intValue]) && [[[[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] componentsSeparatedByString:@"::"] objectAtIndex:0] isEqualToString:@"SELECTEDBUTTON"]) {
            [self mySendDataToPeers:[[NSString stringWithFormat:@"DISCONNECTEDFORSAMEBUTTONPRESSED"] dataUsingEncoding:NSASCIIStringEncoding]];
            [self btnDisconnect:nil];
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"You Were Disconnected" message:@"You were disconnected because both devices were selected to be on the same side" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alertView show];
            NSLog(@"device");
        }
        if(data == [[NSString stringWithFormat:@"DISCONNECTEDFORSAMEBUTTONPRESSED"] dataUsingEncoding:NSASCIIStringEncoding]) {
            [self btnDisconnect:nil];
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"You Were Disconnected" message:@"You were disconnected because both devices were selected to be on the same side" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
            [alertView show];
            NSLog(@"remote device");
        }
        selectionHasBeenChecked = true;
    }
}


- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    touchesArray = [NSMutableArray arrayWithArray:[touches allObjects]];
    nNumTouches = [touchesArray count];
    for (int nTouch = 0;  nTouch < nNumTouches;  nTouch++)
    {
        touch = [touchesArray objectAtIndex:nTouch];
        ptTouch = [touch locationInView:self.view];
    }
    
    touch = [touches anyObject];
    point = [touch locationInView:self.view];
    
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (int i = 0; i < particles.count; i++) {
        Particle *p = [particles objectAtIndex:i];
        [p.image removeFromSuperview];
        [particles removeObjectAtIndex:i];
    }
    [self mySendDataToPeers:[[[NSString alloc] initWithFormat:@"CLEARSCREEN"] dataUsingEncoding:NSASCIIStringEncoding]];
}*/

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    if(selectedButton)
    {
        dataString = [[NSString alloc]initWithFormat:@""];
        touchesArray = [NSMutableArray arrayWithArray:[touches allObjects]];
        nNumTouches = [touchesArray count];
        for (int i = 0; i < nNumTouches; i++) {;
            ptTouch = [[touchesArray objectAtIndex:i] locationInView:self.view];
            previousPoint = [[touchesArray objectAtIndex:i] previousLocationInView:self.view];
            dataString = [dataString stringByAppendingString:[NSString stringWithFormat:@"%f %f %f %f ",ptTouch.x, ptTouch.y, previousPoint.x, previousPoint.y]];
            int maxLifeTime = 10;
        
            for (int i = 0; i < 1; i++) {
                Particle *particle = [[Particle alloc]init:image];
                particle.image.center = ptTouch;
                particle.velocityX = (previousPoint.x - ptTouch.x);
                particle.velocityY = (previousPoint.y - ptTouch.y);
                particle.lifetime = arc4random() % maxLifeTime + 30;
                [particles insertObject:particle atIndex:0];
                [self.view addSubview:particle.image];
            }
        }
        [self mySendDataToPeers:[dataString dataUsingEncoding:NSASCIIStringEncoding]];
    }
    NSLog(@"number: %d Max: %d", particles.count, maxParticles);
}
- (void) update
{
    for (int i = 0; i < particles.count; i++) {
        Particle *p = [particles objectAtIndex:i];
        if(i < maxParticles)
        {
            [p update:image];
           /* if((selectedButton == 1) && (p.image.center.x <= 0))
            {
                p.image.center = CGPointMake(p.image.center.x + totalScreenWidth, p.image.center.y);
                NSLog(@"11");
            }
            if((selectedButton == 1) && (p.image.center.x >= totalScreenWidth))
            {
                p.image.center = CGPointMake(p.image.center.x - totalScreenWidth, p.image.center.y);
                NSLog(@"22");
            }
            if((selectedButton == 2) && (p.image.center.x <= -1.0 * totalScreenWidth))
            {
                p.image.center = CGPointMake(p.image.center.x + totalScreenWidth, p.image.center.y);
                NSLog(@"33");
            }
            if(selectedButton == 2 && p.image.center.x >= [[UIScreen mainScreen] bounds].size.width)
            {
                p.image.center = CGPointMake(p.image.center.x - (2.0 * [[UIScreen mainScreen] bounds].size.width), p.image.center.y);
                NSLog(@"44");
            }
            if(p.image.center.y <= 0)
            {
                p.image.center = CGPointMake(p.image.center.x, p.image.center.y + [[UIScreen mainScreen] bounds].size.height);
                NSLog(@"55"); 
            }
            
            if(p.image.center.y >= [[UIScreen mainScreen] bounds].size.height)
            {
                p.image.center = CGPointMake(p.image.center.x, p.image.center.y - [[UIScreen mainScreen] bounds].size.height);
                NSLog(@"66");
            }*/
        
       if (p.image.center.x <= 0) {
            p.image.center = CGPointMake(totalScreenWidth, p.image.center.y);
            //NSLog(@"11");
        }
        if (p.image.center.x > totalScreenWidth) {
            p.image.center = CGPointMake(0, p.image.center.y);
            //NSLog(@"22");
        }
        if (p.image.center.y <= 0) {
            p.image.center = CGPointMake(p.image.center.x,totalScreenHeight);
           // NSLog(@"33");
        }
        if (p.image.center.y > totalScreenHeight) {
             p.image.center = CGPointMake(p.image.center.x,0);
            //NSLog(@"44");
        }
        
        } else {
            [p.image removeFromSuperview];
            [particles removeObject:p];
        }
        
        
    }
}

@end